import { TagOutlined, SearchOutlined, PlusOutlined, DeleteOutlined } from '@ant-design/icons'
import { keywordCompare } from '@gnlab/utils'
import { useAsyncEffect } from '@gnlab/utils/env-react'
import { Input, Modal, Button, message, Tag, Spin } from 'antd'
import { Empty } from '@/desktop/components'
import { useStreams } from '@/lib/utils'
import services from '@/services'
import './Content.module.less'

import AddModal from './add-or-choose'

export default function Content() {
  const [tags] = useStreams(services.groups.tags)

  const [isLoading, setIsLoading] = useState(false)
  useAsyncEffect(async () => {
    setIsLoading(true)
    const res = await services.groups.loadTags()
    if (!res.success) void message.warning('标签列表加载失败')
    setIsLoading(false)
  }, [])

  const [keyword, setKeyword] = useState('')
  const filteredTags = useMemo(
    () => (keyword.trim() ? tags.filter(tag => keywordCompare(keyword.trim(), tag.name)) : tags),
    [tags, keyword],
  )

  const [adding, setAdding] = useState(false)
  const addFinish = useCallback(() => setAdding(false), [])

  const realRemoveTag = useCallback(async (id: number) => {
    const res = await services.groups.removeTag(id)
    if (res.success) void message.success('标签删除成功')
    else void message.warning(`标签删除失败：${res.error}`)
  }, [])
  const removeTag = useCallback(
    (e: React.MouseEvent<HTMLElement>, id: number) => {
      e.preventDefault()

      Modal.confirm({
        title: '确认删除标签吗？',
        content: '删除后，已添加到群资料的标签也将一起删除',
        onOk: async () => realRemoveTag(id),
      })
    },
    [realRemoveTag],
  )

  // =============================

  const loading = isLoading ? (
    <main styleName="loading">
      <Spin size="large" tip="加载中..." />
    </main>
  ) : null

  const empty =
    !isLoading && !filteredTags.length ? (
      <main styleName="empty">
        <Empty description={tags.length ? '没有匹配的标签' : '尚未创建标签'} />
      </main>
    ) : null

  const main =
    !isLoading && filteredTags.length ? (
      <main>
        <div styleName="tags">
          {filteredTags.map(tag => <Tag
            key={tag.id}
            icon={<TagOutlined />}
            closable
            onClose={e => removeTag(e, tag.id)}
            closeIcon={<DeleteOutlined />}
          >
            {tag.name}
          </Tag>)}
        </div>
      </main>
    ) : null

  return <div styleName="group-tags">
    <header>
      <Button type="primary" icon={<PlusOutlined />} onClick={() => setAdding(true)}>
        新建群标签
      </Button>
      <Input
        placeholder="搜索群标签"
        suffix={<SearchOutlined />}
        value={keyword}
        onInput={e => setKeyword((e.target as HTMLInputElement).value)}
      />
    </header>

    {loading}
    {empty}
    {main}

    <AddModal adding={adding} initialInput={keyword} onFinish={addFinish} />
  </div>
}
